<template>
  <div class="user-bind-device-dialog-page">
    <el-dialog
      :model-value="props.dialogVisible"
      title="绑定设备"
      width="1200px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <div style="display: flex;width: 100%;">
        <div style="width: 250px;height: 500px;overflow-y: auto;">
          <el-tree
            ref="treeRef"
            class="nr-tree"
            :data="treeData"
            :expand-on-click-node="false"
            show-checkbox
            default-expand-all
            node-key="pid"
            highlight-current
            :props="defaultProps"
          />
        </div>

        <div style="width: 910px;margin-left: 16px;">
          <el-form ref="searchParamsRef" :model="searchParams" @submit.prevent="search">
            <el-row :gutter="16">
              <el-col :span="8">
                <el-form-item label="地址搜索：" prop="address">
                  <el-input v-model="searchParams.address" clearable placeholder="请输入地址" style="width: 100%;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="设备搜索：" prop="device">
                  <el-input v-model="searchParams.device" clearable placeholder="请输入设备名称或设备SN" style="width: 100%;"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item>
                  <el-button type="primary" @click="search">查询</el-button>
                  <el-button @click="reset">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <div class="data-block">
            <el-table ref="multipleTableRef" :data="tableData" :height="400" class="nr-table">
              <el-table-column type="selection" width="30"/>
              <el-table-column label="设备名称" prop="deviceName"></el-table-column>
              <el-table-column label="设备SN" prop="deviceSn"></el-table-column>
              <el-table-column label="安装地址" prop="address"></el-table-column>
              <el-table-column label="安装房间" prop="location"></el-table-column>
            </el-table>
            <el-pagination
              class="nr-page"
              v-model:current-page="searchParams.currentPage"
              v-model:page-size="searchParams.pageSize"
              :page-sizes="[10, 20, 30, 40]"
              background
              layout="total, prev, pager, next, sizes, jumper"
              :total="searchParams.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange">
            </el-pagination>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="DeviceDetailDialog">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { projectList } from '@/api/project-manage'
import { deviceListPage } from '@/api/device-manage'
import { bindDeviceBatch } from '@/api/bind'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: {}
  }
})

const defaultProps = {
  children: 'projectTree',
  label: 'projectName',
}
const treeRef = ref<any>(null)
const treeData = ref<any>([])
const searchParamsRef = ref<FormInstance>()
const searchParams = reactive({
  address: '',
  device: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const tableData = ref<any>([])

watch(() => props.dialogVisible, async (newVal) => {
  if (newVal) {
    getProjectData()
    getDeviceData()
  }
})

// 查询
const search = () => {
  searchParams.currentPage = 1
  getDeviceData()
}

// 重置
const reset = () => {
  searchParamsRef.value?.resetFields()
}

// 分页跳转
const handleCurrentChange = (val: number) => {
  getDeviceData()
}
const handleSizeChange = (val: number) => {
  getDeviceData()
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 关闭弹窗
const handleClose = () => {
  resetForm(searchParamsRef.value)
  tableData.value = []
  treeData.value = []
  searchParams.currentPage = 1
  searchParams.pageSize = 10
  searchParams.total = 0
  proxy?.$emit('update:dialogVisible', false)
}

// 提交表单
const handleSubmit = async () => {
  let arr = <any>[...multipleTableRef.value?.getSelectionRows()]
  if (arr.length === 0) {
    ElMessage.error(`未选择设备！`)
    return false
  }
  let deviceIds = <any>[]
  arr.map((item: any) => {
    deviceIds.push(item.deviceId)
  })
  let params = {
    userId: props.formData.id,
    deviceIdList: deviceIds,
  }
  await bindDeviceBatch(params).then((res: any) => {
    if (res.code === 0) {
      ElMessage.success(`绑定成功！`)
      emit('submit')
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}

// 获取项目树表格数据
const getProjectData = async () => {
  await projectList().then((res: any) => {
    if (res.code === 0) {
      treeData.value = [res.data]
      // treeRef.value?.setCheckedKeys([res.data.pid])
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}

// 获取设备表格数据
const getDeviceData = async () => {
  let params = {
    pidList: treeRef.value?.getCheckedKeys(),
    address: searchParams.address,
    deviceNameOrSn: searchParams.device,
    currentPage: searchParams.currentPage,
    pageSize: searchParams.pageSize
  }
  await deviceListPage(params).then((res: any) => {
    if (res.code === 0) {
      tableData.value = [...res.list]
      searchParams.total = res.page.totalSize
    } else {
      ElMessage.error(`${res.msg}`)
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.user-bind-device-dialog-page
  :deep(.el-dialog__body)
    width 100%
    box-sizing border-box
</style>
